#include "VideoScenesInItem.h"

#include <utility>
#include "source/input/InputSourceManager.h"
#include "Util/logc.h"

namespace Media{
    VideoScenesInItem::VideoScenesInItem(VideoScenesInItemConfig  itemConfig):m_itemConfig(std::move(itemConfig)){
        tracef("create VideoScenesInItem");
        m_failNum = 0;
    }
    VideoScenesInItem::~VideoScenesInItem(){
        tracef("~VideoScenesInItem");
    }

    const VideoScenesInItemConfig& VideoScenesInItem::GetItemConfig(){
        return m_itemConfig;
    }

    void VideoScenesInItem::sourceFrameCb(const AVFrame::Ptr& frame){
        if(!m_frames.Push(frame)){
            warnf("frame queue has full, the frame will drop");
        }
    }

    bool VideoScenesInItem::Start(){
        tracef("VideoScenesInItem Start");
        //create inputSource
        auto inputSource = InputSourceManager::Instance()->GetSource(m_itemConfig.m_sourceId);
        if(!inputSource){
            errorf("not found source ,id=%d",m_itemConfig.m_sourceId);
            return false;
        }

        //add frameConsumer
        std::weak_ptr<VideoScenesInItem> wptr = shared_from_this();
        m_consumerId = inputSource->AddVFrameConsumer([wptr](const AVFrame::Ptr& frame){
            auto sptr = wptr.lock();
            if(sptr){
                sptr->sourceFrameCb(frame);
            }
        });

        return inputSource->Start();
    }

    bool VideoScenesInItem::Stop() const{
        auto inputSource = InputSourceManager::Instance()->GetSource(m_itemConfig.m_sourceId);
        if(!inputSource){
            return false;
        }
        inputSource->RemoveVFrameConsumer(m_consumerId);
        return true;
    }


    bool VideoScenesInItem::GetFrame(AVFrame::Ptr& frame){
        if(m_frames.Pop(frame)){
            m_failNum = 0;
            return true;
        }

        return false;
    }

}